﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace IceDog.WebApi.AnythingApi.Services
{
    /// <summary>
    /// 定时执行器
    /// </summary>
    public class TimerExecuter<T>
    {
        private static long _idIndex = 0;
        public TimerExecuter()
        {
            this.Id = _idIndex++;
        }
        /// <summary>
        /// id,不需要赋值
        /// </summary>
        public long Id { get; private set; }
        /// <summary>
        /// 触发间隔(ms)
        /// </summary>
        public long Interval { get; set; }

        /// <summary>
        /// 定时器到时间的时候触发的动作
        /// </summary>
        public Action<T> Action { get; set; }

        /// <summary>
        /// 是否是只执行一次
        /// </summary>
        public bool OnlyOnce { get; set; }

        /// <summary>
        /// 是否是在定时器启动的时候就执行一次
        /// </summary>
        public bool IsHeading { get; set; }

        /// <summary>
        /// 参数数据
        /// </summary>
        public T ArgsData { get; set; }
    }

    /// <summary>
    /// 定时服务
    /// </summary>
    public static class TimerService
    {
        /// <summary>
        /// 定时器集合
        /// </summary>
        public static List<Timer> Timers = new List<Timer>(10);

        /// <summary>
        /// 添加定时器并启动定时器
        /// </summary>
        /// <param name="executer"></param>
        public static void AddAndStart<T>(TimerExecuter<T> executer)
        {
            if (executer.IsHeading)
            {
                try
                {
                    executer.Action(executer.ArgsData);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("定时服务执行动作出错", ex.ToString());
                }

            }
            var timer = new Timer()
            {
                Enabled = true,
                AutoReset = !executer.OnlyOnce,
                Interval = executer.Interval,
            };
            timer.Elapsed += (object sender, ElapsedEventArgs e) => {
                try
                {
                    executer.Action(executer.ArgsData);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("定时服务执行动作出错", ex.ToString());
                }
            };
            timer.Start();
            Timers.Add(timer);
        }

        /// <summary>
        /// 清空所有定时器
        /// </summary>
        public static void ClearAll()
        {
            Timers.ForEach(t => t.Stop());
            Timers.Clear();
        }
    }
}
